<!-- eslint-disable vue/no-mutating-props -->
<script lang="ts" setup>
import { Dialog, Field } from 'vant'
import { MaterialApi } from '~/api/MaterialApi';
import { MaterialModel, OrderItemModel } from '~/model'

const props = withDefaults(defineProps<{
  /** 是否渲染 */
  show: boolean
  /** 当前商品 */
  current?: MaterialModel
  /** 是否显示删除按钮（默认：显示） */
  showDelete?: boolean
  /** 是否显示当前商品（默认：显示） */
  showCurrent?: boolean
  /** 是否展示下架商品（默认：显示） */
  showTakenOff?: boolean
  /** 商品列表Getter */
  sourceGetter?: () => Promise<OrderItemModel[]>
}>(), {
  showDelete: true,
  showCurrent: true,
  showTakenOff: false,
})

const emits = defineEmits([
  'update:show',
  'delete',
  'update:item',
  'update:material',
])

// 搜索框内容
const searchInput = ref('')
const orderItemsAll = ref([] as OrderItemModel[])

const searchInputLower = computed(() => searchInput.value.toLocaleLowerCase())
const orderItemsFiltered = computed(() => {
  if (!searchInput.value) {
    return orderItemsAll.value
  }
  else {
    const ret = orderItemsAll.value.filter((x) => {
      return x.material!.name.toLocaleLowerCase().includes(searchInputLower.value)
        || x.material!.specification.toLocaleLowerCase().includes(searchInputLower.value)
        || x.material!.comment.toLocaleLowerCase().includes(searchInputLower.value)
    })
    if (props.showTakenOff) {
      return ret
    }
    else {
      return ret.filter(x => !x.material?.takenOff)
    }
  }
})

function chooseItem(item: OrderItemModel) {
  emits('update:item', item)
  emits('update:material', item.material)
  close()
}

async function init() {
  orderItemsAll.value = []

  if (props.sourceGetter) {
    orderItemsAll.value = await props.sourceGetter()
  }
  else {
    console.warn('Warning! No sourceGetter')

    // 获取订单，根据订单对物品的引用次数进行物品排序
    // const allOrder = await OrderApi.getAll()
    // const refCounter = new Map<number, number>()
    // for (const order of allOrder) {
    //   for (const item of order.items) {
    //     const id = item.material!.id
    //     const oldVal = refCounter.get(id)
    //     if (oldVal === undefined) {
    //       refCounter.set(id, 1)
    //     }
    //     else {
    //       refCounter.set(id, oldVal + 1)
    //     }
    //   }
    // }

    const materials = await MaterialApi.getAll()
    orderItemsAll.value = materials.map(x => OrderItemModel.fromMaterialModel(x))
    // orderItemsAll.value = materials.map((material) => {
    //   const oim = new OrderItemModel()
    //   oim.material = material
    //   oim.unitPrice = material.unitPrice
    //   return oim
    // })
    // orderItemsAll.value.sort((a, b) => {
    //   const ka = refCounter.get(a.material!.id) || 0
    //   const kb = refCounter.get(b.material!.id) || 0
    //   return kb - ka
    // })
  }
}

function close() {
  searchInput.value = ''
  emits('update:show', false)
}

function handleCloseDelete() {
  close()
  emits('delete')
}

watch(() => props.show, (val) => {
  if (val) {
    init()
  }
})
</script>

<template>
  <Dialog
    :show="show"
    title="选择商品"
    confirm-button-color="red"
    confirm-button-text="删除"
    :show-confirm-button="showDelete"
    :close-on-click-overlay="true"
    @update:show="$emit('update:show', $event)"
    @confirm="handleCloseDelete"
  >
    <div v-if="current && showCurrent" p2>
      当前: {{ current?.name }} {{ current?.specification }}
    </div>
    <Field v-model="searchInput" mb2 placeholder="搜索商品..." bg-light-500 />
    <div h-30vh flex flex-wrap of-auto bg-gray-1>
      <div
        v-for="(item, index) in orderItemsFiltered"
        :key="index"
        of-hidden px4 py2
        style="width:100%"
        @click="chooseItem(item)"
      >
        <span mr2>{{ item.material?.name }}</span>
        <span mr2>{{ item.material?.specification }}</span>
        <span mr2 class="reason">{{ item.unitPrice }}元/{{ item.material?.unit }}</span>
        <br>
        <span mr2 class="reason">备注: {{ item.material?.comment }}</span>
      </div>
    </div>
  </Dialog>
</template>

<style scoped>
.reason {
  font-size: 0.75em;
  color: #000000aa;
}
</style>
